<?php

namespace system\library;

class Route
{
	private static $path = null;

	private static $route = [];

	public static function initialize()
	{
		self::$path = empty($_GET['s']) ? '/index' : $_GET['s'];
		self::$path = str_ireplace('.html', '', self::$path);
	}

	public static function rule($route, $Callback = false, $httpMethod = '*')
	{
		if ($httpMethod == '*') $httpMethod = $_SERVER['REQUEST_METHOD'];
		self::$route[] = [$route, $Callback, $httpMethod];
	}

	public static function end()
	{
		$route_list = self::$route;
		$dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) use ($route_list) {
			foreach ($route_list as $key => $route) {
				$r->addRoute($route[2], $route[0], $route[1]);
			}
		});
		$httpMethod = $_SERVER['REQUEST_METHOD'];
		// self::$path = rawurldecode(self::$path);
		$routeInfo = $dispatcher->dispatch($httpMethod, self::$path);
		switch ($routeInfo[0]) {
			case \FastRoute\Dispatcher::NOT_FOUND:
				return response404();
				break;
			case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
				// ... 405 Method Not Allowed
				return http_response_code(405);
				$allowedMethods = $routeInfo[1];
				break;
			case \FastRoute\Dispatcher::FOUND:
				// ... call $handler with $vars
				$handler = $routeInfo[1];
				$vars = $routeInfo[2];
				return $handler($vars);
				break;
		}
		return false;
	}

	public static function dispatch($dispatcher)
	{
		$dispatcher = \FastRoute\simpleDispatcher($dispatcher);
		$httpMethod = $_SERVER['REQUEST_METHOD'];
		return $dispatcher->dispatch($httpMethod, self::$path);
	}
}
